package com._520it.crm.realm;

import com._520it.crm.domain.Employee;
import com._520it.crm.domain.Permission;
import com._520it.crm.domain.Role;
import com._520it.crm.service.IEmployeeService;
import com._520it.crm.service.IPermissionService;
import com._520it.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm{
    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IPermissionService permissionService;
    @Setter
    private IRoleService roleService;

    @Override
    public String getName() {
        return "UserRealm";
    }

    //授权操作
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        Employee current = (Employee) principal.getPrimaryPrincipal();
        List<String> roles= null;
        List<String> perms= null;
        if(current.isAdmin()){
            roles = new ArrayList<>();
            List<Role> roleList = current.getRoles();
            for (Role role : roleList) {
                roles.add(role.getSn());
                List<Permission> permissions =role.getPermissions();
            }
            perms = new ArrayList<>();
            perms.add("*:*");
        }else{
            roles= roleService.queryRoleSnByEmpId(current.getId());
            perms = permissionService.queryPermissionResourceByEmpId(current.getId());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(perms);
        return info;
    }
    //认证操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Employee current = employeeService.queryByName(username);
        if(current == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(current,current.getPassword(),getName());
        return info;
    }
}
